package com.tim.app.ui.activity.record;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Handler;
import android.text.TextPaint;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.application.library.runtime.event.EventManager;
import com.tim.app.R;
import com.tim.app.constant.EventTag;
import com.tim.app.record.WaveSurfaceView;
import com.tim.app.record.inter.ScrollViewListener;
import com.tim.app.record.utils.DensityUtil;
import com.tim.app.record.utils.SamplePlayer;
import com.tim.app.record.utils.SoundFile;
import com.tim.app.record.view.ObservableScrollView;
import com.tim.app.record.view.WaveformView_2;
import com.tim.app.server.util.DateUtils;
import com.tim.app.ui.activity.BaseActivity;

import java.io.File;
import java.util.Locale;
import java.util.Timer;
import java.util.TimerTask;

/**
 * 录音试听
 */
public class AuditionRecordActivity extends BaseActivity implements ScrollViewListener {

    private static final String TAG = "AuditionRecordActivity";

    private TextView tvRecordTime;

    private RelativeLayout rlWaveContainer;

    private LinearLayout llAudition;//试听
    private ImageView ivRecordAudition;

    private LinearLayout llBack;//返回

    private String mFilename;
    private int totalTime;
    private String fileName;

    private TextView tvCurrentTime;
    private TextView tvTotalTime;

    private LinearLayout ll_wave_content1;
    private LinearLayout timeLine;

    private WaveSurfaceView waveSfv1;
    private WaveformView_2 waveView1;
    private ObservableScrollView mScrollView1;

    private Timer mTimer = new Timer(); // 计时器

    /**
     * 启动录音编辑页面
     *
     * @param context
     */
    public static void start(Context context, String filePath, int totalTime) {
        Intent intent = new Intent(context, AuditionRecordActivity.class);
        intent.setData(Uri.parse(filePath));
        intent.putExtra("time", totalTime / 1000);
        context.startActivity(intent);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_audition_record;
    }

    @Override
    public void initView() {
        tvRecordTime = (TextView) findViewById(R.id.tvRecordTime);

        llAudition = (LinearLayout) findViewById(R.id.llAudition);
        ivRecordAudition = (ImageView) findViewById(R.id.ivRecordAudition);

        llBack = (LinearLayout) findViewById(R.id.llBack);

        rlWaveContainer = (RelativeLayout) findViewById(R.id.rlWaveContainer);
        tvCurrentTime = (TextView) findViewById(R.id.tvCurrentTime);
        tvTotalTime = (TextView) findViewById(R.id.tvTotalTime);

        timeLine = (LinearLayout) this.findViewById(R.id.ll_time_counter);
        ll_wave_content1 = (LinearLayout) this.findViewById(R.id.ll_wave_content1);
        //第一个视图
        waveSfv1 = (WaveSurfaceView) this.findViewById(R.id.wavesfv1);
        waveView1 = (WaveformView_2) this.findViewById(R.id.waveview1);
//		waveView1.setFlag(flagPositions);
        mScrollView1 = (ObservableScrollView) this.findViewById(R.id.hlv_scroll1);
        mScrollView1.setScrollViewListener(this);

        llAudition.setOnClickListener(this);
        llBack.setOnClickListener(this);

        mFilename = getIntent().getData().toString();
        fileName = mFilename.substring(mFilename.lastIndexOf("/") + 1).replace(".wav", "");
        totalTime = getIntent().getIntExtra("time",0);
        tvTotalTime.setText( DateUtils.formatSecond(totalTime) + "");
        timeSize();
        initWaveView();
        timerCounter.start();

        mTimer.schedule(timerTask, 0, 1000);
    }

    @Override
    public void initData() {

    }

    private int totleLength;

    /**
     * 音频的时间刻度
     */
    private void timeSize() {
        timeLine.removeAllViews();
        totleLength = totalTime * DensityUtil.dip2px(60);
//		timeLine1.removeAllViews();
        ll_wave_content1.setLayoutParams(new FrameLayout.LayoutParams(totalTime * DensityUtil.dip2px(60), LinearLayout.LayoutParams.MATCH_PARENT));
        for (int i = 0; i < totalTime; i++) {
            LinearLayout line1 = new LinearLayout(this);
            line1.setOrientation(LinearLayout.HORIZONTAL);
            line1.setLayoutParams(new LinearLayout.LayoutParams(DensityUtil.dip2px(60), LinearLayout.LayoutParams.WRAP_CONTENT));
            line1.setGravity(Gravity.CENTER);

            TextView timeText = new TextView(this);
            timeText.setText(formatTime(i));
            timeText.setWidth(DensityUtil.dip2px(60) - 2);
            timeText.setGravity(Gravity.CENTER_HORIZONTAL);
            TextPaint paint = timeText.getPaint();
            paint.setFakeBoldText(true); //字体加粗设置
            timeText.setTextColor(Color.rgb(204, 204, 204));
            View line2 = new View(this);
            line2.setBackgroundColor(Color.rgb(204, 204, 204));
            line2.setPadding(0, 10, 0, 0);
            line1.addView(timeText);
            line1.addView(line2);
            timeLine.addView(line1);
        }

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.llBack:
                finish();
                break;
            case R.id.llAudition:
                startPlay();
                break;
        }
    }

    /**
     * 开始播放音频文件
     */
    protected void startPlay() {

        if (mPlayer != null && mPlayer.isPlaying()) {
            ivRecordAudition.setSelected(false);
            mPlayer.pause();
            mTimeCounter = -1;
        } else {
            ivRecordAudition.setSelected(true);
            if (mPlayer == null) {
                mScrollView1.scrollTo(0, 0);
                try {
                    mPlayer = new MediaPlayer();
                    mPlayer.setDataSource(mFile1.getAbsolutePath());
                    mPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
                    mPlayer.prepare();
                    mPlayer.start();
                    totalTime = mPlayer.getDuration();
                    mTimeCounter = 0;
                    mPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                        public synchronized void onCompletion(MediaPlayer arg0) {
                            ivRecordAudition.setSelected(false);
                            mScrollView1.scrollTo(totleLength, 0);
                            mTimeCounter = -1;
                            mPlayer = null;
                        }
                    });
                } catch (final java.io.IOException e) {
                    Toast.makeText(this, "文件播放出错！", Toast.LENGTH_SHORT).show();
                }
            } else {
                int start = currentPosition * waveView1.pixelsToMillisecsTotal() / totleLength;
                mTimeCounter = 0;
                mPlayer.seekTo(start);
                mPlayer.start();
            }
        }
    }

    // 计时器
    TimerTask timerTask = new TimerTask() {

        @Override
        public void run() {
            if (mPlayer == null)
                return;
            try {
                if (mPlayer.isPlaying()) {
                    handler.sendEmptyMessage(0); // 发送消息
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    };

    Handler handler = new Handler() {
        public void handleMessage(android.os.Message msg) {
            if (null != mPlayer ) {
                int position = mPlayer.getCurrentPosition();
                int duration = mPlayer.getDuration();
                if (position > 0) {
                    tvCurrentTime.setText(generateTime(position));
                }
            }
        }

    };

    private static String generateTime(long time) {
        int totalSeconds = (int) (time / 1000);

        int seconds = totalSeconds % 60;
        int minutes = (totalSeconds / 60) % 60;
        int hours = totalSeconds / 3600;

        if (hours > 0) {
            return String.format(Locale.US, "%02d:%02d:%02d", hours, minutes,
                    seconds).toString();
        } else {
            return String.format(Locale.US, "%02d:%02d", minutes, seconds)
                    .toString();
        }
    }

    private int currentPosition = 0;

    /**
     * 时间格式化
     *
     * @param timeSec
     * @return
     */
    private String formatTime(int timeSec) {
        if (timeSec < 10) {
            return "00:" + "0" + timeSec;
        }
        if (timeSec >= 10 && timeSec < 60) {
            return "00:" + timeSec;
        }
        if (timeSec >= 60) {
            String str = "";
            int m = timeSec / 60;
            int s = timeSec % 60;
            if (m < 10) {
                str = "0" + m + ":";
            } else {
                str = "" + m + ":";
            }
            if (s < 10) {
                str = str + "0" + s;
            } else {
                str = str + s;
            }
            return str;
        }
        return "";

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {

    }

    private void initWaveView() {
        loadFromFile1();
    }

    Thread mLoadSoundFileThread;
    boolean mLoadingKeepGoing1;
    SamplePlayer mPlayer1;
    private SoundFile mSoundFile1;
    private File mFile1;
    float mDensity1;

    /**
     * 载入wav文件显示波形
     */
    private void loadFromFile1() {
        try {
            Thread.sleep(300);//让文件写入完成后再载入波形 适当的休眠下
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        mFile1 = new File(mFilename);
        mLoadingKeepGoing1 = true;
        mLoadSoundFileThread = new Thread() {
            public void run() {
                try {
                    mSoundFile1 = SoundFile.create(mFile1.getAbsolutePath(), null);
                    if (mSoundFile1 == null) {
                        return;
                    }
                    mPlayer1 = new SamplePlayer(mSoundFile1);
                } catch (final Exception e) {
                    e.printStackTrace();
                    return;
                }
                if (mLoadingKeepGoing1) {
                    Runnable runnable = new Runnable() {
                        public void run() {
                            finishOpeningSoundFile1();
                        }
                    };
                    AuditionRecordActivity.this.runOnUiThread(runnable);
                }
            }
        };
        mLoadSoundFileThread.start();
    }

    /**
     * waveview载入波形完成
     */
    private void finishOpeningSoundFile1() {
        DisplayMetrics metrics = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(metrics);

        mDensity1 = metrics.density;

        waveView1.setSoundFile(mSoundFile1);
        waveView1.recomputeHeights(mDensity1);
    }

    @Override
    public void onScrollChanged(ObservableScrollView scrollView, int x, int y, int oldx, int oldy, boolean isByUser) {
        currentPosition = x;
//        if (x == 0) {
//            tvCurrentTime.setText("00:00");
//        } else {
//            int currentSecond = waveView1.pixelsToMillisecsTotal() / totleLength;
//            if (currentSecond == 0) {
//                if (x > (totleLength / 2)) {
//                    tvCurrentTime.setText("00:01");
//                } else {
//                    tvCurrentTime.setText("00:00");
//                }
//            } else {
//                int t = x * waveView1.pixelsToMillisecsTotal() / totleLength / 1000;
//                tvCurrentTime.setText(formatTime(t));
//            }
//        }
        mScrollView1.scrollTo(x, 0);
    }

    @Override
    protected void onPause() {
        super.onPause();
    }

    private MediaPlayer mPlayer;

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mPlayer != null && mPlayer.isPlaying()) {
            mPlayer.stop();
            mPlayer.release();
            mPlayer = null;
        }
        //注销定时器
        timer_speed.cancel();
        timer_speed = null;
        mPlayer = null;
    }

    private int mTimeCounter = -1;
    private Timer timer_speed;
    private Thread timerCounter = new Thread(new Runnable() {
        @Override
        public void run() {
            try {
                TimerTask timerTask_speed = new TimerTask() {
                    @Override
                    public void run() {
                        if (mTimeCounter != -1) {
                            mTimeCounter = mTimeCounter + 1;
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    if (null != mPlayer) {
                                        mScrollView1.scrollTo((totleLength * mPlayer.getCurrentPosition()) / mPlayer.getDuration(), 0);
                                    }
                                }
                            });
                        }
                    }
                };
                if (timer_speed == null) {
                    timer_speed = new Timer();
                }
                timer_speed.schedule(timerTask_speed, 0, 10);
            } catch (Exception e) {
                e.printStackTrace();
            }

        }
    });

    /**
     * 更新录音的时间
     *
     * @param time
     */
    public void updateRecordTime(String time) {
        tvRecordTime.setText(getString(R.string.recordTime, time));
    }


    @Override
    protected void onResume() {
        super.onResume();
    }

}
